/**
 * @author 甜圆
 * @version v1.0.1
 * @date 2025/8/25 15:57
 * @package PACKAGE_NAME
 * @copyright 甜圆
 */
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class TeacherServer {
    public static void main(String[] args) {
        int port = 8002;

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器启动，端口：" + port + "，等待客户端连接...");

            // 等待客户端连接
            try (Socket clientSocket = serverSocket.accept();
                 ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
                 PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {

                System.out.println("客户端已连接：" + clientSocket.getInetAddress());

                // 读取客户端发送的老师列表
                @SuppressWarnings("unchecked")
                List<Teacher> teachers = (List<Teacher>) in.readObject();

                // 遍历并打印老师信息
                System.out.println("收到的老师信息：");
                for (int i = 0; i < teachers.size(); i++) {
                    Teacher t = teachers.get(i);
                    System.out.printf("%d. 姓名：%s，年龄：%d，工资：%.2f%n",
                            i + 1, t.getName(), t.getAge(), t.getSalary());
                }

                // 将老师信息写入本地文件
                try (BufferedWriter writer = new BufferedWriter(new FileWriter("teacher.txt"))) {
                    for (Teacher t : teachers) {
                        writer.write(String.format("%s-%d-%.2f%n",
                                t.getName(), t.getAge(), t.getSalary()));
                    }
                    System.out.println("老师信息已成功写入teacher.txt");
                }

                // 向客户端返回"ok"
                out.println("ok");

            } catch (ClassNotFoundException e) {
                System.out.println("接收数据格式错误：" + e.getMessage());
            } catch (IOException e) {
                System.out.println("处理客户端数据出错：" + e.getMessage());
            }

        } catch (IOException e) {
            System.out.println("服务器启动失败：" + e.getMessage());
        }
        System.out.println("服务器已关闭");
    }
}

